#include "objpool.h"
#include <stdlib.h>
#include <stdio.h>

struct obj_pool* objpool_build(size_t unit, size_t count) {
	static size_t poolsize = sizeof(struct obj_pool);
	struct obj_pool *ppool = (struct obj_pool*) malloc(poolsize);
//printf("pool's addr is %d\n",(int)ppool);
	ppool->length = count;
	ppool->unit = unit;
	char *pdata = (char *) malloc(unit * count);
	ppool->datablock = pdata;
//printf("datablock's addr is %d\n",(int)pdata);

	static size_t nodesize = sizeof(struct obj_node);
	struct obj_node *objarr = (struct obj_node*) malloc(nodesize * count);
	size_t i = 0;
//printf("objarr's addr is %d\n",(int)objarr);
	for (; i < count; i++) {
		objarr[i].obj = pdata + (i * unit);
		objarr[i].used = 0;
	}
	ppool->obj_arr = objarr;
	return ppool;
}

int objpool_release(struct obj_pool *objpool) {
//printf("pool's addr is %d\n",(int)objpool);
	struct obj_node *objarr = objpool->obj_arr;
//printf("objarr's addr is %d\n",(int)objarr);
	void *pdata = objpool->datablock;
//printf("datablock's addr is %d\n",(int)pdata);
	free(pdata);
	free(objarr);
	free(objpool);
	return 0;
}

void* object_new(struct obj_pool *pool) {
	size_t count = pool->length;
	struct obj_node *objarr = pool->obj_arr;
	void *data = NULL;
	size_t i = 0;
	for (; i < count; i++) {
		if (!objarr[i].used) {
			data = objarr[i].obj;
			objarr[i].used = 1;
			break;
		}
	}
	return data;
}

int object_del(struct obj_pool *pool, void *object) {
	size_t count = pool->length;
	struct obj_node *objarr = pool->obj_arr;

	size_t i = 0;
	for (; i < count; i++) {
		if (object == objarr[i].obj) {
			objarr[i].used = 0;
			break;
		}
	}
	return 0;
}
